import React, { useEffect } from 'react';

export default function MaxAsync() {
    let asyncItem = (index) => {
        return new Promise((resolve, rejected) => {
            setTimeout(() => {
                resolve(index);
            }, 100);
        });
    };

    /**
     * 
     * @param {*} total 总请求数量
     * @param {*} max 单次最大并行数量
     */
    const readMaxAsync = (total, max) => {
        let fillArr = new Array(total).fill(false);
        let fakeFetch = Array.from({ length: total }, (v, k) => k );
        // 当前完成数量
        let count = 0;

        return new Promise((resolve, rejected) => {
            while (count < max) {
                next();
            }

            function next() {
                let current = count++;
                if (current >= total) {
                    // 请求全部完成就将promise置为成功状态，然后将result座位promise值返回
                    !fillArr.includes(false) && resolve(fillArr);
                    return;
                }
                const params = fakeFetch[current];
                asyncItem(params).then((res) => {
                    fillArr[current] = res;
                    if (current < total) {
                        next();
                    }
                });
            }
        });
    };

    useEffect(() => {
        readMaxAsync(6, 5).then((res) => {
            console.log(res);
        });
    }, []);
    return (
        <div>
           max
        </div>
    );
}